﻿//===============================================================================
// Microsoft Innovation Centre - Western Europe
// Copyright (c) 2008 Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================

using System;
using System.IO;
using System.ServiceModel.Syndication;
using System.Xml;
using System.Xml.Linq;
using Microsoft.WVB.Framework.Entities;

namespace Microsoft.WVB.Framework
{
    public abstract class EntityVisitor
    {
        protected SyndicationItem item { get; set; }
        public void VisitEntity(BaseEntity entity, XElement element)
        {
            if ((entity != null) && (element != null))
            {
                StringReader sr = new StringReader(element.ToString(SaveOptions.None));
                XmlReader xr = XmlReader.Create(sr);
                item = SyndicationItem.Load(xr);

                VisitProperties(entity);
                VisitCategories(entity);
                VisitUris(entity);
            }
            else
            {
                throw new ArgumentNullException();
            }
        }

        protected virtual void VisitProperties(BaseEntity entity)
        {
            entity.ID = item.Id;
        }

        protected virtual void VisitCategories(BaseEntity entity)
        {
            foreach (SyndicationCategory category in item.Categories)
            {
                entity.InternalCategories.Add(category.Name);
            }
        }

        protected virtual void VisitUris(BaseEntity entity)
        {
            foreach (SyndicationLink link in item.Links)
            {
                if (link.RelationshipType.Contains("related"))
                    entity.Related.Add(link.Uri);

                if (link.RelationshipType.Contains("edit"))
                    entity.Edit = link.Uri;

                if (link.RelationshipType.Contains("self"))
                    entity.Self = link.Uri;
            }
        }
    }
}
